<?php
	function updateScore($pin, $nickname, $device, $score, $last)
	{
		$con = mysql_connect ("localhost", "db_user", "db_pass");

		if (!$con) {die('Could not connect: ' . mysql_error());}

		$db_selected = mysql_select_db("db_database", $con);

		$sql = "SELECT * FROM Ranking WHERE pin = '".$pin."'";
		$result = mysql_query ($sql, $con);

        if (mysql_num_rows($result) === 0)
        {
        	$sql = "INSERT INTO Ranking (pin, nickname, device, score, last) VALUES ('" .$pin. "', '" .$nickname. "', '" .$device. "', '" .$score. "', '" .$last. "')";
        	if (!mysql_query($sql, $con))
        	{
        		die('Error: ' .mysql_error());
        	}

        	echo "OK";
        } else {
        	$sql = "UPDATE Ranking SET nickname = '" .$nickname. "', device = '" .$device. "', score = '" .$score. "', last= '" .$last. "' WHERE pin = '" .$pin. "'";
            if (!mysql_query($sql, $con))
            {
                die('Error: ' .mysql_error());
            }

            echo "UPDATED";
        }

		mysql_close($con);	
	}

	function queryRinking()
	{
		$con = mysql_connect ("localhost", "db_user", "db_pass");

		if (!$con) {die('Could not connect: ' . mysql_error());}

		$db_selected = mysql_select_db("db_database", $con);

       	$result = array();	
		$rs = mysql_query("select count(*) from Ranking");
		$row = mysql_fetch_row($rs);
		$result["total"] = intval($row[0]);

		$sql=" SELECT nickname, score, last FROM Ranking ORDER BY score DESC LIMIT 0 , 10";
		$rs = mysql_query($sql);
  
		$items = array();
		while($row = mysql_fetch_object($rs))
		{
            array_push($items, $row);
		}
		$result["ranking"] = $items;

		echo json_encode($result);

		mysql_close($con);	
	}
?>